package com.i2bt.app;

import com.i2bt.common.AndroidRestContract;
import com.i2bt.common.UserConfig;

import com.i2bt.app.login.LoginActivity;
import com.i2bt.bean.AbstractBean;
import com.i2bt.util.HttpNetroidUtil;
import com.i2bt.util.HttpPostTask;
import com.i2bt.util.HttpPostTask.OnAsyncTaskListener;

import android.app.Activity;
import android.app.ProgressDialog;

import com.duowan.mobile.netroid.Listener;
import com.duowan.mobile.netroid.NetroidError;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.LinkedList;
import java.util.Queue;

/**
 * 
 * Title : 基础发送接收json模型
 * 
 * Description : 通过继承此类来完成打包和解包json的逻辑, 最后通过响应的 操作来调用fragment或activity
 * 
 * CreatedTime : 2014-8-12
 * 
 * @author wuliao & kakaxi & yi
 * 
 * @version 1.0
 * 
 */

public abstract class BaseJsonModel {

	private boolean isResponse = true; // 是否响应, 默认是接受响应

	private boolean isSilent; // 是否沉默

	protected BaseActivity activity; // 当前使用碎片的上下文

	protected BaseFragment fragment; // 当前使用的碎片

	protected JSONObject jsonParam; // 统一使用的json参数类

	protected AbstractBean beanParam; // 统一使用的bean参数类

	protected String jsonStrParam; // 统一使用的json字符串参数类

	private String url;
	
	private jsonListener listener; // 监听器

	private static Queue<HttpPostTask> taskQueue = new LinkedList<HttpPostTask>(); // 任务队列
	
	private ProgressDialog progress; // 进度框

	private BaseJsonModel() {
		jsonParam = new JSONObject();
		
		listener = new jsonListener();
	}

	public BaseJsonModel(BaseActivity activity) {
		this();
		this.activity = activity;
		
		//创建进度对话框
		progress = new ProgressDialog(activity);
		progress.setMessage("请稍等..");
		//不可按返回键取消
		progress.setCancelable(true);
	}

	public BaseJsonModel(BaseFragment fragment) {
		this((BaseActivity) fragment.getActivity());
		this.fragment = fragment;
	}

	/**
	 * 打包逻辑, 在这里做判断调用. 例如自己写一些登陆, 注册的打包方法 然后就 用这个来判断参数里面act要操作的方法然后调用对应的方法,
	 * 当打包成json字 符串后, 这个也返回那个json字符串. 之后就自动执行访问请求!
	 * 
	 * @return
	 */
	abstract protected String logicToWrap() throws JSONException;

	/**
	 * 解包逻辑, 在这里判断后解包并对activity做操作
	 * 
	 * @param isSuc
	 * @param result
	 */
	abstract protected void logicToUnwrap(boolean isSuc, String result)
			throws JSONException;

	public void basepost(String url, AbstractBean beanParam) {
		this.url = url;
		this.beanParam = beanParam;
		try {
			String paramJsonStr;
			paramJsonStr = logicToWrap();
			sendPostRequest(url, paramJsonStr);
		} catch (JSONException e) {
			e.printStackTrace();
			fragment.toastHandler("发送请求时json包装有误!");
		}
	}

	/**
	 * 使用这个方法来打包参数并访问服务器
	 * 
	 * @param url
	 * @param beanParam
	 */
	public void postTo(String url, AbstractBean beanParam) {
		int result = this.activity.CheckAndLogin();
		if (result == 0) {
			basepost(url, beanParam);
		} else if (result == 1) {
			this.url = url;
			this.beanParam = beanParam;
			postLogin();
		}
	}

	public void postLogin() {
		try {
			JSONObject json = new JSONObject();
			json.put(AndroidRestContract.ACTION, AndroidRestContract.LOGIN);
			json.put(AndroidRestContract.USER_ID, UserConfig.userId);
			json.put(AndroidRestContract.PASSWORD, UserConfig.password);

//			HttpPostTask postTask = new HttpPostTask(activity,
//					AndroidRestContract.REST_LOGIN, json.toString(),
//					isResponse, true);
//			postTask.setOnAsyncTaskListener(this);
//			postTask.execute();
			
			HttpNetroidUtil.postRequest(url, json, listener);

		} catch (JSONException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 发送post请求
	 * 
	 * @param url
	 * @param param
	 */
	private void sendPostRequest(String url, String param) {
//		HttpPostTask postTask = null;
//		if (isSilent) {
//			postTask = new HttpPostTask(activity, url, param, isResponse, true);
//		} else {
//			postTask = new HttpPostTask(activity, url, param, isResponse);
//		}
//		postTask.setOnAsyncTaskListener(this);
//		postTask.execute();
		
		try {
			progress.show();
			System.out.println(param);
			HttpNetroidUtil.postRequest(url, new JSONObject(param), listener);
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 返回结果, 调用解包逻辑
	 */
	public void taskResult(boolean isSuc, String result) {
		int res = this.activity.CheckAndLogin();
		System.out.println(result);
		if (res == 0) {
			try {
				logicToUnwrap(isSuc, result);
			} catch (JSONException e) {
				e.printStackTrace();
				activity.toastHandler("json处理有误!");
			}
			return;
		} else if (res == 1) {
			if (isSuc) {
				try {
					JSONObject ja = new JSONObject(result);
					boolean succ = ja.getBoolean(AndroidRestContract.SUCCEED);
					String mes = null;
					if (succ) {
						mes = ja.getString(AndroidRestContract.TOKEN);
						UserConfig.token = mes;
						mes = ja.getString(AndroidRestContract.NICK_NAME);
						UserConfig.userName = mes;
						System.out.println("后台登陆Token:" + UserConfig.token);
						System.out.println("后台登陆nickname:"
								+ UserConfig.userName);
						postTo(url, beanParam);
					} else {
						this.activity.toastHandler("登陆失败!请重新登录");
						this.activity.goActivityAndFinish(LoginActivity.class);
						return;
					}

				} catch (JSONException e) {
					e.printStackTrace();
				}
			} else {
				this.activity.toastHandler("网络连接失败");
				return;
			}
		}

	}
	
	class jsonListener extends Listener<JSONObject> {

		@Override
		public void onSuccess(JSONObject result) {
			taskResult(true, result.toString());
			if (progress.isShowing()) {
				progress.hide();
			}
		}
		
		@Override
		public void onError(NetroidError error) {
			super.onError(error);
//			taskResult(false, error.toString());
			activity.toastHandler("hehe:" + error.toString());
			if (progress.isShowing()) {
				progress.hide();
			}
		}
		
	}

	/**
	 * 是否返回响应值, 默认是true
	 * 
	 * @param isResponse
	 */
	public void setIsResponse(boolean isResponse) {
		this.isResponse = isResponse;
	}

	/**
	 * 打包同样的json串
	 * 
	 * @throws JSONException
	 */
	protected void wrapCommonJson() throws JSONException {
		jsonParam = new JSONObject();
		jsonParam
				.put(AndroidRestContract.REQUEST_ID, System.currentTimeMillis())
				.put(AndroidRestContract.ACTION, beanParam.getAct())
				.put(AndroidRestContract.TOKEN, UserConfig.token)
				.put(AndroidRestContract.USER_ID, UserConfig.userId)
				.put(AndroidRestContract.HOMEBOX_ID, UserConfig.homeboxId);
	}

	/**
	 * 把字符串数组打包成json数组
	 * 
	 * @param strs
	 *            路径数组
	 * @return
	 */
	protected JSONArray strsToJsonArray(String[] strs) {

		JSONArray jsonArray = new JSONArray();
		for (String path : strs) {
			jsonArray.put(path);
		}
		return jsonArray;
	}

	/**
	 * 先不管
	 * 
	 * @param url
	 * @return
	 */
	public String getTo(String url) {
		return null;
	}

	/**
	 * 先不管
	 * 
	 * @param url
	 * @param param
	 */
	public void sendGetRequest(String url, String param) {
	}

	public boolean isSilent() {
		return isSilent;
	}

	public void setSilent(boolean isSilent) {
		this.isSilent = isSilent;
	}

}
